package com.joven.core.utils.lockUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.UUID;

/**
 * @author joven_wong
 * 2021/6/30 11:10
 * redis分布式锁
 * 版本问题 额外引入jedis客户端依赖
 * jedis.set(String key, String value, String nxxx, String expx, int time)
 * 第三个为nxxx，这个参数我们填的是NX，意思是SET IF NOT EXIST，即当key不存在时，我们进行set操作；若key已经存在，则不做任何操作。
 */
@Service
public class JedisDistributedLock {

    @Autowired
    JedisConnectionFactory jedisConnectionFactory;

    /**
     * 占用锁
     * @param lockKey 锁key
     * @return 锁id
     */
    public String occupyDistributedLock(String lockKey) {
        //获得jedis实例
        Jedis jedis = (Jedis) jedisConnectionFactory.getConnection().getNativeConnection();
        //锁id（必须拥有此id才能释放锁）
        String lockId = UUID.randomUUID().toString();
        //占用锁同时设置失效时间
        String isSuccees = jedis.set(lockKey, lockId, "NX", "PX", 15000);
        //占用锁成功返回锁id，否则返回null
        if ("OK".equals(isSuccees)) {
            return lockId;
        } else {
            return null;
        }
    }

    /**
     * 释放锁
     * @param lockKey 锁key
     * @param lockId 加锁id
     */
    public boolean releaseDistributedLock(String lockKey,String lockId) {
        if(lockId != null){
            //获得jedis实例
            Jedis jedis = (Jedis) jedisConnectionFactory.getConnection().getNativeConnection();
            //执行Lua代码删除lockId匹配的锁
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(lockId));
            return true;
        }
        return false;
    }

}
